package todo;

import done.AbstractWashingMachine;
import se.lth.cs.realtime.*;

public class WaterController extends PeriodicThread {
	private AbstractWashingMachine theMachine;
	private int mode;
	private double targetlevel;
	private boolean ack;
	private boolean fill;
	private WaterEvent e;
	private WaterEvent tmp;

	public WaterController(AbstractWashingMachine theMachine, long speed) {
		super(speed);
		this.theMachine = theMachine;
		mode = WaterEvent.WATER_IDLE;
		targetlevel = 0.5;
		ack = false;
		fill = false;
	}

	public void perform() {
		tmp = (WaterEvent) mailbox.tryFetch();
		if (tmp != null) {
			e = tmp;
			targetlevel = e.getLevel();
			mode = e.getMode();
			ack = true;
		}

		if (mode == WaterEvent.WATER_IDLE) {
			theMachine.setDrain(false);
			theMachine.setFill(false);
		} else if (mode == WaterEvent.WATER_FILL) {
			fill = true;

			if (theMachine.getWaterLevel() >= targetlevel) {
				fill = false;
				if (ack) {
					((WashingProgram) e.getSource())
							.putEvent(new AckEvent(this));
					ack = false;
				}
			}
			theMachine.setDrain(false);
			theMachine.setFill(fill);

		} else if (mode == WaterEvent.WATER_DRAIN) {
			if (theMachine.getWaterLevel() == 0) {
				if (ack) {
					((WashingProgram) e.getSource())
							.putEvent(new AckEvent(this));
					ack = false;
				}
			}
			theMachine.setDrain(true);
			theMachine.setFill(false);
		}
	}
}
